import { route } from "quasar/wrappers";
import {
  createRouter,
  createMemoryHistory,
  createWebHistory,
  createWebHashHistory,
  routerKey,
} from "vue-router";
import routes from "./routes";

import { LocalStorage, SessionStorage } from "quasar";

import { ACCESS_TOKEN } from "src/stores/mutation-types";

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */

export default route(function (/* { store, ssrContext } */) {
  const createHistory = process.env.SERVER
    ? createMemoryHistory
    : process.env.VUE_ROUTER_MODE === "history"
    ? createWebHistory
    : createWebHashHistory;

  const Router = createRouter({
    scrollBehavior: () => ({ left: 0, top: 0 }),
    routes,

    // Leave this as is and make changes in quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    history: createHistory(
      process.env.MODE === "ssr" ? void 0 : process.env.VUE_ROUTER_BASE
    ),
  });

  //判断是否登录
  Router.beforeEach(function (to, from, next) {
    if (to.meta.requireAuth) {
      //从cookie中获取用户信息，判断是否已登录
      if (SessionStorage.getItem(ACCESS_TOKEN)) {
        next(); //表示已经登录
      } else {
        //未登录
        //next可以传递一个路由对象作为参数 表示需要跳转到的页面
        next({
          name: "UserLogin",
          query: { redirect: to.fullPath }, //登录后再跳回此页面时要做的配置
        });
      }
    } else {
      //表示不需要登录
      next(); //继续往后走
    }
  });

  return Router;
});
